<?php
/**
 * Created by PhpStorm.
 * User: dale
 * Date: 2017/12/21
 * Time: 下午4:28
 */

namespace Admin\Frontend\Controllers;


use Admin\Models\hrm\XhhrmDepart;
use Admin\Models\res\XhresArticle;
use Admin\Models\school\XhschoolExamine;
use Admin\Models\school\XhschoolInfo;
use Admin\Models\school\XhschoolState;
use Admin\Models\school\XhschoolStateNode;
use Admin\Models\stats\XhstatsExamine;
use Admin\Models\sys\XhsysEnum;
use Admin\Models\sys\XhsysGrade;
use Helpers\Assets;
use Helpers\HttpClient;
use Helpers\Main;
use Helpers\Template;
use Helpers\Tool;
use Helpers\User;
use Helpers\UserPower;
use Helpers\XhException;
use Modules\School;
use Phalcon\Db\Adapter\Pdo\Mysql;
use Services\BigData;

class SchoolExamineController extends ControllerBase
{


    public static $enums = [
        'iArea' => [ 1 => '部门' , 2 => '区域' , 3 => '市' ],
    ];

    public static $config = [
        ['sTag' => 'tchUse'     , 'sName' => '教师使用熟练程度' , 'bPrecise' => 1 , 'iMaxGrade' => 30 , 'mStandard' => '达标老师占比百分率算分'  ],
        ['sTag' => 'runExamine' , 'sName' => '运营绩效考核统计' , 'bPrecise' => 1 , 'iMaxGrade' => 30 , 'mStandard' => '当月运营考核分数算分'    ],
        ['sTag' => 'tchShare'   , 'sName' => '教师交流分享次数' , 'bPrecise' => 1 , 'iMaxGrade' => 5  , 'mStandard' => '4次以上满分'        ],
        ['sTag' => 'pubClass'   , 'sName' => '公开课次数'       , 'bPrecise' => 1 , 'iMaxGrade' => 5  , 'mStandard' => '3次以上满分'        ],
        ['sTag' => 'tchActive'  , 'sName' => '教师活跃率'       , 'bPrecise' => 1 , 'iMaxGrade' => 5  , 'mStandard' => '教师活跃度'        ],
        ['sTag' => 'stuActive'  , 'sName' => '学生活跃率'       , 'bPrecise' => 1 , 'iMaxGrade' => 5  , 'mStandard' => '学生活跃度'        ],
        ['sTag' => 'runCase'    , 'sName' => '运营案例分享次数' , 'bPrecise' => 1 , 'iMaxGrade' => 5  , 'mStandard' => '部门一次5分，区域4分，市里2分，满分5' ],
        ['sTag' => 'exCase'     , 'sName' => '运营案例'         , 'bPrecise' => 1 , 'iMaxGrade' => 5  , 'mStandard' => '一次5分，满分5分' ],
        ['sTag' => 'task'       , 'sName' => '需求bug资源次数'  , 'bPrecise' => 1 , 'iMaxGrade' => 2  , 'mStandard' => '最高2分' ],
        ['sTag' => 'weekly'     , 'sName' => '周报次数'         , 'bPrecise' => 1 , 'iMaxGrade' => 5  , 'mStandard' => '一个月4次' ],
        ['sTag' => 'tchLog'     , 'sName' => '教师日志次数'     , 'bPrecise' => 1 , 'iMaxGrade' => 5  , 'mStandard' => '实际考核老师数目（一次以上）/ 需考核老师总数 > 90%以上满分' ],
        ['sTag' => 'feedback'   , 'sName' => '回复/反馈次数'    , 'bPrecise' => 1 , 'iMaxGrade' => 3  , 'mStandard' => '回复率90%以上满分' ],
        ['sTag' => 'exTch'      , 'sName' => '重要教师的使用(附加)'  , 'bPrecise' => 1 , 'iMaxGrade' => 5  , 'mStandard' => '重要老师和关键老师使用达标满分' ],
        ['sTag' => 'activity'   , 'sName' => '学校活动'          , 'bPrecise' => 1 , 'iMaxGrade' => 10   , 'mStandard' => '校际10分，含两个年级的校内活动8分，一个年级的校内活动5分，1个班级活动2分，2个班以上4分' ],
    ];

    public static $runLevel = [ 1 => '优秀' , 2 => '良好' , 3 => '合格' , 4 => '不合格'];

    public function checkEndDate($endDate)
    {
        //用于检查最后一天是不是超过了当前时间，如果是则统计到今天的零点
        if (strtotime($endDate) >= strtotime(date('Y-m-d'))) {
            return date("Y-m-d", strtotime('-1 day'));
        }
        return $endDate;
    }

    /**
     * 获取教师对应的年级
     *
     * @param $schoolId
     *
     * @return array
     *
     * create by dale  20180928
     */
    public function getTchInfo($schoolId)
    {
        $builder = $this->modelsManager->createBuilder()
            ->columns(['u.iUserId AS id', 't.iCurGrade AS grade'])
            ->from(['u' => '\\Admin\\Models\\user\\XhsysUser'])
            ->leftJoin('\\Admin\\Models\\sys\\XhsysUserTch', 'u.iUserId = t.iUserId', 't')
            ->where('u.bDelete = 0 AND u.bDisable = 0 AND u.bHistory = 0')
            ->andWhere('u.iUserType = 4 AND u.iSchoolId = :schoolId:', ['schoolId' => $schoolId]);
        $builder->andWhere('t.iType = 1');       //计入考核教师
        $data = $builder->getQuery()->execute()->toArray();
        $enum = XhsysEnum::getEnumByNodeName('年级');
        Tool::runEnum($data, ['grade' => $enum]);
        $tchInfo = array_column($data, 'grade', 'id');
        return $tchInfo;
    }

    /**
     * 获取当前学校的年级
     *
     * @param $schoolId
     *
     * @return array
     *
     * create by dale  20180928
     */
    public function getSchoolGrade($schoolId)
    {
        $builder = $this->modelsManager->createBuilder()
            ->columns(['u.iUserId AS id', 't.iCurGrade AS grade'])
            ->from(['u' => '\\Admin\\Models\\user\\XhsysUser'])
            ->leftJoin('\\Admin\\Models\\sys\\XhsysUserTch', 'u.iUserId = t.iUserId', 't')
            ->where('u.bDelete = 0 AND u.bDisable = 0 AND u.bHistory = 0')
            ->andWhere('u.iUserType = 4 AND u.iSchoolId = :schoolId:', ['schoolId' => $schoolId])
            ->andWhere('t.iType = 1') //计入考核老师
            ->groupBy('t.iCurGrade');
        $data = $builder->getQuery()->execute()->toArray();
//        $enum = XhsysEnum::getEnumByNodeName('年级');
//        Tool::runEnum($data, ['grade' => $enum]);
        $grade = array_values(array_filter(array_column($data, 'grade')));
        return $grade;
    }



    /**
     * 获取学校成绩
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20171226
     */
    public function getGradeAction()
    {
        if (!UserPower::checkUserPower('School_RunState_Edit')) {
            return $this->sendErrorResponse(401, '没有权限');
        }
        $schoolId   = $this->request->getPost('schoolId');
        $month      = $this->request->getPost('month');
        if (!$schoolId) {
            return $this->sendErrorResponse(500, '缺少schoolId');
        }
        if (!$month) {
            $month = $this->getMonthAction();
        }
        try {
            $examineMode = XhschoolInfo::find([
                'columns'    => 'iExamineMode,iSchoolId',
                'conditions' => 'bDelete = 0 and iSchoolId = :id:',
                'bind'       => ['id' => $schoolId],
            ])->toArray();
            $examineMode = array_column($examineMode, 'iExamineMode', 'iSchoolId');
            $gradeEnum = XhsysEnum::getEnumByNodeName('年级');
            $examineType = Tool::getValue($examineMode, $schoolId, 1);
            if ($examineType == 1) {
                $arr = $this->dealData($schoolId, $month);
                $res = $this->saveData($arr, '全校');
                if (!$res) {
                    throw  new \Exception('错误信息');
                }
            } elseif ($examineType == 2) {
                //年级考核
                $gradeArr = $this->getSchoolGrade($schoolId);
                if (!$gradeArr) {
                    throw new \Exception('没有年级数据');
                }

                foreach ($gradeArr as $grade) {
                    $arr = $this->dealData($schoolId, $month, $grade);
                    $res = $this->saveData($arr, $gradeEnum[$grade]);
                    if (!$res) {
                        throw  new \Exception('错误信息');
                    }
                }
                $this->saveAvgGrade($schoolId, $month);
            }
            return $this->sendSuccessResponse('保存成功');
        } catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 获取学校平均分
     *
     * @param $schoolId
     * @param $month
     * @throws XhException
     *
     * create by dale  20180929
     */
    public function saveAvgGrade($schoolId, $month)
    {
        $gradeArr = $this->getSchoolGrade($schoolId);
        if (!$gradeArr) {
            throw new XhException('无法计算平均分，该学校没有分年级');
        }
        $gradeEnum = XhsysEnum::getEnumByNodeName('年级');
        foreach ($gradeArr as &$grade) {
            $grade = $gradeEnum[$grade];
        }
        $nodeGrade = XhschoolState::find([
            'columns'    => 'iTotalGrade',
            'conditions' => 'bDelete = 0 and iSchoolId = :iSchoolId: and sMonth = :sMonth: and sGrade in ({grades:array}) ',
            'bind'       => ['iSchoolId' => $schoolId, 'sMonth' => $month, 'grades' => $gradeArr],
        ])->toArray();
        if ($nodeGrade) {
            $nodeGrade = array_column($nodeGrade, 'iTotalGrade');
            $totalGrade = array_sum($nodeGrade) / count($nodeGrade);
            $totalGrade = intval($totalGrade);
            $state = XhschoolState::findFirst([
                'conditions' => 'bDelete= 0 and iSchoolId = :iSchoolId: and sMonth = :sMonth: and sGrade = :sGrade:',
                'bind'       => ['iSchoolId' => $schoolId, 'sMonth' => $month, 'sGrade' => '全校'],
            ]);
            if (!$state) {
                $state = new XhschoolState();
            }
            $state->iMode  = 2;
            $state->sGrade = '全校';
            $state->iSchoolId = $schoolId;
            $state->sMonth = $month;
            $state->iTotalGrade = $totalGrade;
            $state->iLevel = $this->getRunLevel($totalGrade, true);
            if (!$state->save()) {
                throw new XhException('平均成绩保存失败');
            }
        } else {
            throw new XhException('未查询到学校年级成绩');
        }
    }

    /**
     * 获取教师布置次数
     *
     * @param $schoolId
     * @param $month
     * @param $grade
     *
     * @return array
     *
     * create by dale  20180928
     * modify by dale 20180928  添加年级区分
     */
    public function getTchJson($schoolId, $month, $grade = null)
    {
//        $sql  = "select  u.iUserId,u.iSchoolId  from XHSys_User as u LEFT JOIN XHSys_UserTch as t ON u.iUserId = t.iUserId WHERE u.iSchoolId = {$schoolId} AND u.iUserType =4  and  u.bDelete = 0 and u.bCompany = 0 and u.bDisable = 0 and u.bHistory = 0 and t.iType = 1 ";
        $sql  = "select  u.iUserId,u.iSchoolId,t.iCurGrade  from XHSys_User as u LEFT JOIN XHSys_UserTch as t ON u.iUserId = t.iUserId WHERE u.iSchoolId = {$schoolId} AND u.iUserType =4  and  u.bDelete = 0 and u.bDisable = 0 and u.bHistory = 0 and t.iType = 1 ";
        if ($grade) {
            $sql .= " and  t.iCurGrade = {$grade} ";
//            $data = $this->db->fetchAll($sql);
//            var_dump($data);die;

        }
        $data = $this->db->fetchAll($sql);
        if (!$data) {
            return [];
        }
        $fixNum = $this->getTchFixNum($schoolId, $month);
        $arr = [];
        foreach ($data as $index => $row) {
            $arr[] = ['userId'=>$row['iUserId'] ,'fixNum'=>(isset($fixNum[$row['iUserId']]) ? $fixNum[$row['iUserId']] : 0)];
        }
        return $arr;
    }

    /**
     * 生成等级
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by xjq 20180602
     */
    public function generateLevelAction()
    {
        $month = $this->request->getQuery('month', 'string');
        if (!$month) {
            return $this->sendErrorResponse(400, '缺少参数');
        }
        $states = XhschoolState::find([
            'conditions' => 'bDelete = 0  and sMonth = :sMonth: ',
            'bind'       => ['sMonth' => $month]
        ]);
        foreach ($states as $state) {
            $state->iLevel = $this->getRunLevel($state->iTotalGrade, true);
            if (!$state->save()) {
                return $this->sendErrorResponse(500, '保存失败');
            }
        }
        return $this->sendSuccessResponse('保存成功');
    }


    public function getActivity($schoolId,$month)
    {
        $sql = "select sTag,iArtId,sTargetIds,iCreateUserId,sTitle  from XHRes_Article  where DATE_FORMAT(tStartTime,'%Y-%m') = '{$month}' AND iSchoolId = {$schoolId} and bDelete = 0 and iArtType = 9 and iState = 2 ";
        return $this->db->fetchAll($sql);
    }


    /**
     * 数据处理
     *
     * @param $schoolId
     * @param $month
     * @param $grade
     * @return array
     * @throws \Exception
     *
     * create by dale 20180119
     */
    public function dealData($schoolId, $month, $grade = null)
    {
        try {
            $arr = [];
            $arr['sMonth'] = $month;
            $arr['iSchoolId'] = $schoolId;
            //教师使用熟练程度iTchUseRate
            $arr['iTchUseRate'] = $this->getTchUseRate($schoolId, $month, $grade);
//            var_dump($arr['iTchUseRate']);die;
            //iRunExamine
            $arr['iRunExamine'] = $this->getRunExamine($schoolId, $month, $grade);

            //iTchShareNum
            $arr['iTchShareNum'] = $this->getShareNum($schoolId, $month, $grade);

            //iPClassNum
            $arr['iPClassNum'] = $this->getClassNum($schoolId, $month, $grade);


            //iStuActiveRate
            $arr['iStuActiveRate'] =  $this->getStuActive($schoolId, $month);
//            $arr['iStuActiveRate'] = 10;
            //iTchActiveRate
            $arr['iTchActiveRate'] = $this->getTchActive($schoolId, $month);
//            $arr['iTchActiveRate'] = 10;

            //mRunCase
            $arr['mRunCase'] = $this->getRunCase($schoolId, $month);


            //iTaskNum
            $arr['iTaskNum'] = $this->getTaskNum($schoolId, $month);

            //iWeekNum
            $arr['iWeekGrade'] = $this->getWeekGrade($schoolId, $month);


            //iLogNum
            $arr['iLogNum'] = $this->getLogNum($schoolId, $month, $grade);

            //反馈统计
            $arr['mFeedback'] = $this->getFeedback($schoolId, $month);


            $arr['iExCaseGrade'] = $this->getExcGrade($schoolId, $month);

            $arr['mActivity'] = $this->getActivity($schoolId, $month);

            //教师使用详情
//            $arr['mTchJSon'] = json_encode($this->getTchJson($schoolId,$month));
            $arr['mTchJSon'] = $this->getTchJson($schoolId, $month, $grade);

            $arr['iImpTchUse'] = $this->getImpTchUse($schoolId, $month, $grade);
            $arr['iExcTchUse'] = $this->getExcTchUse($schoolId, $month, $grade);
            if ($arr['iImpTchUse'] == 100 && $arr['iExcTchUse'] == 100) {
                $arr['iKeyTchUse'] = 5;
            } else {
                $arr['iKeyTchUse'] = 0;
            }
            $arr['iTotalGrade'] = $this->getUseGrade($arr['iTchUseRate']) + $this->getRunGrade($arr['iRunExamine']);
            $arr['iTotalGrade'] += $this->getShareGrade($arr['iTchShareNum']) + $this->getPClassGrade($arr['iPClassNum']);
            $arr['iTotalGrade'] += $this->getActiveGrade($arr['iTchActiveRate']) + $this->getActiveGrade($arr['iStuActiveRate']);
            $arr['iTotalGrade'] += $this->getRunCaseGrade($arr['mRunCase']);
            $arr['iTotalGrade'] += $this->getFeedbackGrade($arr['mFeedback']);
            $arr['iTotalGrade'] += $arr['iTaskNum'] > 0 ? 2 : 0;
            $arr['iTotalGrade'] += $arr['iWeekGrade'];
            $arr['iTotalGrade'] += $arr['iExCaseGrade'];
            $arr['iTotalGrade'] += ($arr['iLogNum']/$this->getTchStandard($schoolId, $grade, true))>=0.9 ? 5 : 0;
            $arr['iTotalGrade'] += $arr['iKeyTchUse'];

            return $arr;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

//    /**
//     * 数据库转移
//     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
//     * create by xjq 20180515
//     */
//    public function changeDbAction(){
//        try{
//            $data = XhschoolExamine::find([
//                'columns'    => 'iSchoolId,sMonth,iTchUseRate,iRunExamine,iTchShareNum,iPClassNum,iTchActiveRate,
//            iStuActiveRate,iKeyTchUse,iTotalGrade,iRunCaseNum,iTaskNum,iWeekNum,iLogNum,iImpTchUse,iExcTchUse,
//            mTchJSon,mRunCase,mFeedback,iExCaseNum',
//                'conditions' => 'bDelete = 0'
//            ])->toArray();
//            foreach ($data as &$row){
//                $row['mTchJSon'] = json_decode($row['mTchJSon'],true);
//                $row['mRunCase'] = json_decode($row['mRunCase'],true);
//                $row['mFeedback'] = json_decode($row['mFeedback'],true);
//                $this->saveData($row);
//            }
//            return $this->sendSuccessResponse('数据库转移成功');
//        }catch (\Exception $e){
//            return $this->sendErrorResponse(500 , $e->getMessage());
//        }
//    }

    /**
     * 修改周报bug为满分
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by xjq 20180515
     */
    public function fixGradeAction()
    {
        try {
            $states = XhschoolState::find([
                'conditions' => 'bDelete = 0  and sMonth = :sMonth:',
                'bind'       => ['sMonth' => '2018-04'],
            ]);
            $this->db->begin();
            foreach ($states as $state) {
                $grade = 0;
                $nodes = XhschoolStateNode::find([
                    'conditions' => 'bDelete = 0  and  iSSId = :iSSId:',
                    'bind'       => ['iSSId' => $state->iSSId]
                ]);
                foreach ($nodes as $node) {
                    if ($node->sTag == 'weekly' || $node->sTag == 'task') {
                        $node->iGrade = $node->iMaxGrade;
                        if (!$node->save()) {
                            $this->db->rollback();
                            return $this->sendErrorResponse(500, '保存失败');
                        }
                    }
                    $grade  += $node->iGrade;
                }

                $state->iTotalGrade = $grade; //修改总分
                $state->iLevel      = $this->getRunLevel($grade, true);
                if (!$state->save()) {
                    $this->db->rollback();
                    return $this->sendErrorResponse(500, '保存失败');
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('反馈和周报已修改至满分');

        } catch (\Exception $e) {
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }


//    public function fixTchUseAction(){
//        $states = XhschoolState::find([
//            'conditions' => 'bDelete = 0 ',
//        ]);
//    }




    /**
     * 数据保存
     *
     * @param $arr
     * @param $type
     * @return bool
     * @throws \Exception
     *
     * create by xjq 20180512
     * modify by ck 20180521    保留原始得分
     */
    public function saveData($arr, $type = '全校')
    {
        try {
            $config = self::$config;
            $this->db->begin();
            $state = XhschoolState::findFirst([
                'conditions' => 'iSchoolId = :iSchoolId: AND sMonth = :sMonth: AND bDelete = 0 AND sGrade = :sGrade: ',
                'bind'       => ['iSchoolId' => $arr['iSchoolId'] , 'sMonth' => $arr['sMonth'], 'sGrade' => $type ]
            ]);
            if (!$state) {
                $state = new XhschoolState();
            }
            $state->iSchoolId    = $arr['iSchoolId'];
            $state->sMonth       = $arr['sMonth'];
            $state->iTotalGrade  = $arr['iTotalGrade'];
            $state->sGrade       = $type;
            $grade = null;
            if ($type != '全校') {
                $state->iMode = 2;
                $gradeEnum = XhsysEnum::getEnumByNodeName('年级');
                $gradeEnum = array_flip($gradeEnum);
                $grade = isset($gradeEnum[$type]) ? $gradeEnum[$type] : null;
            } else {
                $state->iMode = 1;
            }

            if (!$state->save()) {
                throw new \Exception('学校状态父节录入失败');
            }
//            if ($type != '全校') {
//                var_dump($arr['mTchJSon']);die;
//            }
            $totalGrade = 0;
            foreach ($config as $index => $row) {
                $node = XhschoolStateNode::findFirst([
                    'conditions' => 'iSSId = :iSSId: and sTag = :sTag:' ,
                    'bind'       => ['iSSId' => $state->iSSId , 'sTag' => $row['sTag'] ]
                ]);
                if (!$node) {
                    $node = new XhschoolStateNode();
                }
                $row['iSSId'] = $state->iSSId;
                switch ($row['sTag']) {
                    case  'tchUse' :
                        $row['iGrade']    = $this->getUseGrade($arr['iTchUseRate']);
                        $row['sRealData'] = $arr['iTchUseRate'];
                        $row['mJson']     = json_encode($arr['mTchJSon']);
                        break;
                    case  'runExamine':
                        $row['iGrade']    = $this->getRunGrade($arr['iRunExamine']);
                        $row['sRealData'] = $arr['iRunExamine'];
                        break;
                    case  'tchShare' :
                        $row['iGrade']    = $this->getShareGrade($arr['iTchShareNum']);
                        $row['sRealData'] = $arr['iTchShareNum'];
                        break;
                    case  'pubClass' :
                        $row['iGrade']     = $this->getPClassGrade($arr['iPClassNum']);
                        $row['sRealData']  = $arr['iPClassNum'];
                        break;
                    case  'tchActive' :
                        $row['iGrade']     = $this->getActiveGrade($arr['iTchActiveRate']);
                        $row['sRealData']  = $arr['iTchActiveRate'];
                        break;
                    case  'stuActive' :
                        $row['iGrade']     = $this->getActiveGrade($arr['iStuActiveRate']);
                        $row['sRealData']  = $arr['iStuActiveRate'];
                        break;
                    case  'runCase' :
                        $row['iGrade']     = $this->getRunCaseGrade($arr['mRunCase']);
                        $row['sRealData']  = array_sum(array_values($arr['mRunCase']));
                        $row['mJson']      = json_encode($arr['mRunCase']);
                        break;
                    case  'exCase' :
                        $row['iGrade']     = $arr['iExCaseGrade'];
                        $row['sRealData']  = $arr['iExCaseGrade'];
                        break;
                    case  'task' :
                        $row['iGrade']     = $arr['iTaskNum'] > 0 ? 2 : 0;
                        $row['sRealData']  = $arr['iTaskNum'];
                        break;
                    case  'weekly':
                        $row['iGrade']     = $arr['iWeekGrade'];
                        $row['sRealData']  = $arr['iWeekGrade'];
                        break;
                    case  'tchLog' :
                        $tchNum = $this->getTchStandard($arr['iSchoolId'], $grade,true);
                        $row['iGrade']     = ($arr['iLogNum'] / $tchNum) >= 0.9 ? 5 : 0;
                        $row['sRealData']  = ''.$arr['iLogNum'] . "/" . $tchNum ."({$this->getTchStandard($arr['iSchoolId'],$grade)})" ;
                        break;
                    case  'feedback':
                        $row['iGrade']     =$this->getFeedbackGrade($arr['mFeedback']);
                        $row['sRealData']  = Tool::getValue($arr['mFeedback'] , 'totalReplied' ,  0) . '/'.Tool::getValue($arr['mFeedback'] , 'totalFeedback',  0);
                        $row['mJson']      = json_encode($arr['mFeedback']);
                        break;
                    case  'exTch' :
                        $row['iGrade']     = ($arr['iImpTchUse'] == 100 && $arr['iExcTchUse'] == 100) ? 5 : 0;
                        $row['sRealData']  = '重要老师使用率'.$arr['iImpTchUse'].'%;优秀老师使用率'.$arr['iExcTchUse'].'%';
                        $row['mJson']      = json_encode(['impTchUse' => $arr['iImpTchUse'] , 'excTchUse' => $arr['iExcTchUse']  ]);
                        break;
                    case 'activity':
                        $row['iGrade']  = $this->getActivityGrade($arr['mActivity']);
                        $row['sRealData'] = count($arr['mActivity']).'次';
                        $row['mJson']     = json_encode($arr['mActivity']);
                        break;
                    default :break;
                }
                if ($node->bLock == null || $node->bLock == 0) {
                    //保留原始数据
                    $row['iCopyGrade'] = $row['iGrade'];
                    $node->assign($row);
                    if (!$node->save()) {
                        throw new \Exception('节点保存失败');
                    }
                }
                $totalGrade += $node->iGrade;
            }
            $state->iTotalGrade = $totalGrade;
            $state->iLevel      = $this->getRunLevel($totalGrade, true);
            if (!$state->save()) {
                throw new \Exception('父节点成绩更新失败');
            }
            $this->db->commit();
            return true; //数据保存成功
        } catch (\Exception $e) {
            $this->db->rollback();
            throw new \Exception($e->getMessage());
        }
    }


    /**
     *
     * @param $data
     * @return int
     * create by xjq 20180605
     */
    public function getActivityGrade($data)
    {
        if (count($data) <= 0) {
            return 0;
        }
        $arr = [];
        foreach ($data as $row){
            $arr[$row['sTag']][] = $row;
        }
        $grade = 0;
        foreach ($arr as $index => $rows) {
            $levelGrade = 0;
            if ($index == 1 && count($rows) > 0) { //校际一次10分
                return 10;
            } else if ($index == 2 && count($rows) > 0 ) { //校内
                foreach ($rows as $row) {
                    $gradeNum = count(explode(',', $row['sTargetIds']));
                    if ($gradeNum == 1) {
                        $levelGrade += 5;
                    } else if ($gradeNum >= 2) {
                        $levelGrade += 8;
                    }
                }
                $grade += $levelGrade >= 8 ? 8 : $levelGrade;
            } else if ($index == 3 && count($rows) > 0 ) {
                foreach ($rows as $row) {
                    $gradeNum = count(explode(',' , $row['sTargetIds']));
                    if ( $gradeNum == 1 ) {
                        $levelGrade += 2;
                    } else if( $gradeNum >= 2 ) {
                        $levelGrade += 4;
                    }
                }
                $grade += $levelGrade >= 4 ? 4 : $levelGrade;
            } else { //不属于任何类型

            }
        }
        return $grade >= 10 ?  10 : $grade;
    }


    /**
     * 优秀分享次数
     * create by xjq 20180509
     */
    public function getExcGrade($schoolId, $month)
    {
        $grade = XhsysGrade::findFirst([
            'conditions' => 'bDelete = 0 and sMonth = :month: and iTargetId = :schoolId: and iType = 1 ',
            'bind'       => ['month' => $month , 'schoolId' => $schoolId ],
        ]);
        if (!$grade) {
            return 0;
        }
        return Tool::getValue($grade->toArray(),'iGrade',0);
    }



    /**
     * 执行生成
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20180119
     */
    public function generateAction()
    {
        if (!UserPower::checkUserPower('School_RunState_Edit')) {
            return $this->sendErrorResponse(401, '没有权限');
        }
        $schoolIds = $this->request->getPost('schoolIds');
        $month     = $this->request->getPost('month');
        if (!$month) {
            $month = $this->getMonthAction();
        }
        $errorNum   = 0;
        $successNum = 0;
        $totalNum   = count($schoolIds);
        if ($totalNum <= 0) {
            return $this->sendErrorResponse('未选择学校，无需执行');
        }
        if ($schoolIds) {
            $examineMode = XhschoolInfo::find([
                'columns'    => 'iExamineMode,iSchoolId',
                'conditions' => 'bDelete = 0 and iSchoolId in ({ids:array})',
                'bind'       => ['ids' => $schoolIds],
            ])->toArray();
            $examineMode = array_column($examineMode, 'iExamineMode', 'iSchoolId');
            $gradeEnum = XhsysEnum::getEnumByNodeName('年级');
            foreach ($schoolIds as $schoolId) {
                try {
                    $examineType = Tool::getValue($examineMode, $schoolId, 1);
                    if ($examineType == 1) {
                        $arr = $this->dealData($schoolId, $month);
                        $res = $this->saveData($arr, '全校');
                        if (!$res) {
                            throw  new \Exception('错误信息');
                        } else {
                            $successNum++;
                        }
                    } elseif ($examineType == 2) {
                        //年级考核
                        $gradeArr = $this->getSchoolGrade($schoolId);
                        if (!$gradeArr) {
                            throw new \Exception('没有年级数据');
                        }
                        foreach ($gradeArr as $grade) {
                            $arr = $this->dealData($schoolId, $month, $grade);
                            $res = $this->saveData($arr, $gradeEnum[$grade]);
                            if (!$res) {
                                throw  new \Exception('错误信息');
                            } else {
                                $successNum++;
                            }
                        }
                        $this->saveAvgGrade($schoolId, $month);
                    }

                } catch (\Exception $e) {
                    $errorNum++;
                    continue;
                }
            }
        }
        return $this->sendSuccessResponse('共计执行'.$totalNum.'次，成功'.$successNum.'次，失败'.$errorNum.'次,执行完毕');
    }

    /**
     * 执行全部
     *
     * create by dale 20180412
     */
    public function generateAllAction()
    {
        $month = $this->request->getQuery('month', 'string');
        $getSchool = $this->request->getQuery('getSchool', 'string');
        $schoolId  = $this->request->getQuery('schoolId', 'int');
        if ($getSchool &&$getSchool == 'true') {
            return $this->sendJsonResponse(XhschoolInfo::getSchoolSupportArray(true, true));
        } else {
            if (!$schoolId) {
                return $this->sendErrorResponse(500, '缺少schoolId');
            }
            if (!$month) {
                $month = $this->getMonthAction();
            }
            try {
                $examineMode = XhschoolInfo::find([
                    'columns'    => 'iExamineMode,iSchoolId',
                    'conditions' => 'bDelete = 0 and iSchoolId = :id:',
                    'bind'       => ['id' => $schoolId],
                ])->toArray();
                $examineMode = array_column($examineMode, 'iExamineMode', 'iSchoolId');
                $gradeEnum = XhsysEnum::getEnumByNodeName('年级');
                $examineType = Tool::getValue($examineMode, $schoolId, 1);
                if ($examineType == 1) {
                    $arr = $this->dealData($schoolId, $month);
                    $res = $this->saveData($arr, '全校');
                    if (!$res) {
                        throw  new \Exception('错误信息');
                    }
                } elseif ($examineType == 2) {
                    //年级考核
                    $gradeArr = $this->getSchoolGrade($schoolId);
                    if (!$gradeArr) {
                        throw new \Exception('没有年级数据');
                    }

                    foreach ($gradeArr as $grade) {
                        $arr = $this->dealData($schoolId, $month, $grade);
                        $res = $this->saveData($arr, $gradeEnum[$grade]);
                        if (!$res) {
                            throw  new \Exception('错误信息');
                        }
                    }
                    $this->saveAvgGrade($schoolId, $month);
                }
//                $arr = $this->dealData($schoolId, $month);
//                $res = $this->saveData($arr);
                if ($res) {
                    return $this->sendSuccessResponse('更新成功');
                }
            } catch (\Exception $e){
                return $this->sendErrorResponse(500 , $e->getMessage());
            }
        }
    }



    //5.教师学生日活跃度
    private function getActiveGrade($activeRate){
        $activeRate = intval($activeRate/10);
        $activeRate =  $activeRate > 10 ? 10 : $activeRate;
        switch ($activeRate){
            case 10 : return 5;
            case 9  : return 5;
            case 8  : return 4;
            case 7  : return 3;
            case 6  : return 2;
            case 5  : return 1;
            case 4  : return 1;
            default : return 0;
        }
    }
    //4.公开课次数
    private function getPClassGrade($classNum){
        switch ($classNum){
            case 0  : return 0;
            case 1  : return 3;
            case 2  : return 4;
            default : return 5;
        }
    }
    //3.教师分享次数
    private function getShareGrade($shareNum){
        switch ($shareNum){
            case 0  : return 0;
            case 1  : return 2;
            case 2  : return 3;
            case 3  : return 4;
            default : return 5;
        }
    }
    //2.运营部绩效考核
    private function getRunGrade($runExamine){
        $runExamine =  intval($runExamine/10);
        $runExamine =  $runExamine > 10 ? 10 : $runExamine;
        switch ($runExamine){
            case 10 : return 30;
            case 9  : return 30;
            case 8  : return 27;
            case 7  : return 24;
            case 6  : return 21;
            case 5  : return 18;
            case 4  : return 15;
            case 3  : return 12;
            case 2  : return 9;
            case 1  : return 6;
            default : return 0;
        }
    }

    //1.教师使用熟练度
    private function getUseGrade($tchUseRate){
        $tchUseRate = intval($tchUseRate/10);
        $tchUseRate = $tchUseRate > 10 ? 10 : $tchUseRate;
        switch ($tchUseRate){
            case 10 : return 30;
            case 9  : return 30;
            case 8  : return 27;
            case 7  : return 24;
            case 6  : return 21;
            case 5  : return 18;
            case 4  : return 15;
            case 3  : return 12;
            case 2  : return  9;
            case 1  : return  6;
            default : return  0;
        }
    }


    //运营案例分享处理
    private function getRunCaseGrade($runCase){
        $total = 0 ;
        foreach ($runCase as $index => $num) {
            switch ($index){
                case 1 : $total += $num * 5 ; break;
                case 2 : $total += $num * 4 ; break;
                case 3 : $total += $num * 2 ; break;
                default: break;
            }
        }
        return $total > 5 ? 5 : $total ;
    }

    //反馈处理
    private function getFeedbackGrade($feedback){
        $feedbackNum = Tool::getValue($feedback, 'totalFeedback',  0);
        $replyNum    = Tool::getValue($feedback, 'totalReplied' ,  0);
        if($feedbackNum == 0 ){ //如果反馈数目为零
            return 0 ;
        }
        if(floatval(intval($replyNum)/intval($feedbackNum)) >= 0.9  &&  $feedbackNum != 0){
            return 3;
        }else{
            return 0;
        }
    }

    //运营服务考核分级
    private function getRunLevel($totalGrade,$isData=false){
        $grade = intval($totalGrade/10) > 10 ? 10 : intval($totalGrade/10);
        if(!$isData){
            switch($grade){
                case 10:
                case 9 : return '<small class="badge  badge-square " title="'.$totalGrade.'" style="color: white;background-color: green;">优秀</small>';
                case 8 :
                case 7 : return '<small class="badge  badge-square " title="'.$totalGrade.'" style="color: white;background-color: #00aced">良好</small>';
                case 6 :
                case 5 : return '<small class="badge  badge-square " title="'.$totalGrade.'" style="color: white;background-color: darkgrey">合格</small>';
                default: return '<small class="badge  badge-square " title="'.$totalGrade.'" style="color: white;background-color: orangered">不合格</small>';
            }
        }else{
            switch($grade){
                case 10:
                case 9 : return 1;
                case 8 :
                case 7 : return 2;
                case 6 :
                case 5 : return 3;
                default: return 4;
            }
        }
    }



    //获取等级
    private function getLevel($totalGrade){
        $grade = intval($totalGrade/10) > 10 ? 10 : intval($totalGrade/10);
        switch($grade){
            case 10:
            case 9 : return '优秀';
            case 8 :
            case 7 : return '良好';
            case 6 :
            case 5 : return '合格';
            default: return "不合格";
        }
    }





    /**
     * 获取教师日志评分标准
     * @param $schoolId
     * @param $grade
     * @param $bLog
     * @return int
     * @throws \Exception
     * create by dale 2018/1/2
     * modify by dale 20180815 添加日志标准
     */
    public function getTchStandard($schoolId ,$grade = null,$bLog = false){
        $sql = "select count(u.iUserId) as nums  from XHSys_User as u LEFT JOIN XHSys_UserTch as t ON  u.iUserId = t.iUserId WHERE u.iSchoolId = '{$schoolId}' AND u.iUserType = 4 and  u.bDelete = 0 and u.bDisable = 0 and u.bHistory = 0 and t.iType = 1 ";
        if ($grade) {
            $sql .= " and  t.iCurGrade = {$grade}  ";
        }
        if ($bLog) {
            $sql .= ' and  t.bStatsLog = 1 ';
        }
        $tchNums = $this->db->fetchOne($sql)['nums'];

        return intval($tchNums);
    }



    /**
     * 获取学校数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20171222
     */
    public function getSchoolDataAction($month){
        try{
            if(!$month){
                $month = date('Y-m',time());
            }
            $schoolExamines = XhschoolExamine::find([
                'conditions' => 'bDelete = 0 AND sMonth = :sMonth:',
                'bind'       => ['sMonth' => $month]
            ]);
            $schoolExamines = $schoolExamines->toArray();
            if (count($schoolExamines) <= 0) {
                return $this->sendErrorResponse(500,'数据库里没有记录');
            }
            return $this->sendJsonResponse($schoolExamines);
        }catch (\Exception $e){
            return $this->sendErrorResponse(500,$e->getMessage());
        }
    }

    /**
     * 获取日期
     *
     * @param bool $showStartEnd
     * @return array|false|string
     * modify by dale 20180417 规则修改为target设置时间或者上一周的时间
     */
    public function getMonthAction($showStartEnd=false)
    {
        $targetMonth = Main::getConfigByName('examine')['schoolStateMonth'];

        if(!$targetMonth){
            $targetMonth = date('Y-m',strtotime('-1 month'));
        }
        return $targetMonth;
    }



    /**
     * 获取教师使用率
     *
     * @param $schoolId
     * @param $month
     * @param $grade
     *
     * @return int
     * @throws \Exception
     * create by dale 20171229
     */
    public function getTchUseRate($schoolId, $month, $grade = null)
    {
//        $sql = "select count(u.iUserId) as num  from XHSys_User as u LEFT JOIN XHSys_UserTch as t ON  u.iUserId = t.iUserId WHERE u.iSchoolId = '{$schoolId}' AND u.iUserType = 4 and  u.bDelete = 0 and u.bCompany = 0 and u.bDisable = 0 and u.bHistory = 0 and t.iType = 1 ";
        $sql = "select  u.iUserId   from XHSys_User as u LEFT JOIN XHSys_UserTch as t ON  u.iUserId = t.iUserId WHERE u.iSchoolId = '{$schoolId}' AND u.iUserType = 4 and  u.bDelete = 0 and u.bDisable = 0 and u.bHistory = 0 and t.iType = 1  ";
        if ($grade) {
            $sql .= " and t.iCurGrade = {$grade} ";
        }
        $tchIdArr = $this->db->fetchAll($sql);
        $tchIdArr = array_values(array_filter(array_column($tchIdArr, 'iUserId')));
        $tchNum = count($tchIdArr);

        $source = $this->getTchFixNum($schoolId,$month);
        if (!$source) {
            return 0;
        }
        $schoolConfig = Main::getConfigByName('school');
        if(!isset($schoolConfig['tchUseStandard'])){
            throw new \Exception('缺少评分标准');
        }
        $goalNum = 0;//达标人员
        foreach ($source  as $index => $value) {
            if (in_array($index, $tchIdArr) && $value >= $schoolConfig['tchUseStandard']) {
                $goalNum++;
            }
        }
//        $sql = "select count(u.iUserId) as tchNum from XHSys_User  as u
//                    LEFT JOIN XHSys_UserTch as t ON t.iUserId = u.iUserId
//                    WHERE u.iSchoolId = '{$schoolId}' AND u.iUserType = 4 and  u.bDelete = 0 and u.bCompany = 0 and u.bDisable = 0 and u.bHistory = 0 AND t.iProficiency = 1 ";
//        $tchSNums = $this->db->fetchOne($sql)['tchNum'];
//        var_dump($goalNum);
//        var_dump($tchNum);
//        var_dump(intval(floatval($goalNum/$tchNum)*100));die;
        return intval(floatval($goalNum/$tchNum)*100);
    }

    /**
     * 获取分享次数
     *
     * @param $schoolId
     * @param $month
     * @param $grade
     * @return mixed
     *
     * create by dale 20171229
     * modify by dale 20180928  添加年级区分
     */
    public function getShareNum($schoolId, $month, $grade = null)
    {
        $dateArr = explode('-',$month);
        $startDay = date('Y-m-d',mktime(0, 0, 0, $dateArr[1],1 , $dateArr[0]));
        $endDay   = date('Y-m-d',strtotime("$startDay +1 month")-24*3600);
        $endDay   = $this->checkEndDate($endDay);
        $sql = "select count(iSSId) as num from XHSchool_Share WHERE  iSchoolId = '{$schoolId}' AND DATE_FORMAT(tTime,'%Y-%m-%d') >= '{$startDay}' AND  DATE_FORMAT(tTime,'%Y-%m-%d') <= '{$endDay}' AND bDelete = 0 ";
        if ($grade) {
            $sql .= " and  iGrade = {$grade} ";
//            var_dump($this->db->fetchOne($sql));die;
        }

        return $this->db->fetchOne($sql)['num'];
    }

    /**
     * 获取公开课次数
     * @param $schoolId
     * @param $month
     * @param $grade
     * @return mixed
     *
     * create by dale 20171229
     * modify by dale 20180928
     */
    public function getClassNum($schoolId,$month,$grade = null)
    {
        $dateArr = explode('-',$month);
        $startDay = date('Y-m-d',mktime(0, 0, 0, $dateArr[1],1 , $dateArr[0]));
        $endDay   = date('Y-m-d',strtotime("$startDay +1 month")-24*3600);
        $endDay   = $this->checkEndDate($endDay);
        $sql = "select count(p.iPCId) as num,u.iSchoolId from XHSchool_PublicClass as p 
                LEFT JOIN XHSys_User as u ON u.iUserId = p.iUserId ";
        if (!$grade) {
            $sql .= " WHERE p.bDelete = 0 AND DATE_FORMAT(p.tStartTime,'%Y-%m-%d') >= '{$startDay}' AND  DATE_FORMAT(p.tStartTime,'%Y-%m-%d') <= '{$endDay}' AND u.iSchoolId = '{$schoolId}' ";
        } else { //区分年级
            $sql .= " LEFT JOIN XHSys_UserTch as ut ON p.iUserId = ut.iUserId ";
            $sql .= " WHERE p.bDelete = 0 AND DATE_FORMAT(p.tStartTime,'%Y-%m-%d') >= '{$startDay}' AND  DATE_FORMAT(p.tStartTime,'%Y-%m-%d') <= '{$endDay}' AND u.iSchoolId = '{$schoolId}' ";
            $sql .= " AND ut.iCurGrade = {$grade} ";
        }
        return $this->db->fetchOne($sql)['num'];
    }

    /**
     * 获取学生月活跃
     *
     * @param $schoolId
     * @param $month
     * @return int
     * create by dale 20171229
     */
    public function getStuActive($schoolId, $month){
        try {
            $activeData = BigData::getActive($schoolId,$month,1);
            if (isset($activeData[0])) {
                $activeData = $activeData[0];
            } else {
                return 0;
            }
            $studentActiveRate = Tool::getValue($activeData, 'studentActiveRate', 0);
            if ($studentActiveRate) {
                return $studentActiveRate*100;
            } else {
                return 0;
            }
        }catch (XhException $e){
            throw  new \Exception($e->getMessage());
        }
    }

//    public function testAction(){
//        $month = '2018-05';
//        $schoolId = 149;
//        $dateArr = explode('-',$month);
//        $endDay   = date('Y-m-d',mktime(0, 0, 0, (($dateArr[1]+1)%12),1 , date('Y'))-24*3600);
//        $endDay   = $this->checkEndDate($endDay);
//        var_dump($endDay);
//        $sql = "select schoolid,SUM(monthstunum) as stuNum from user_alive_count
//                  where DATE_FORMAT(datetime,'%Y-%m-%d') = '{$endDay}' AND schoolid = '{$schoolId}' ";
//        var_dump($sql);die;
//    }

    /**
     * 获取教师日活跃
     *
     * @param $schoolId
     * @param $month
     * @return int
     * @throws \Exception
     * create by dale 20171229
     */
    public function getTchActive($schoolId,$month){
        try{
            $activeData = BigData::getActive($schoolId,$month,1);
            if (isset($activeData[0])) {
                $activeData = $activeData[0];
            } else {
                return 0;
            }
            $teacherActiveRate = Tool::getValue($activeData, 'teacherActiveRate', 0);
            if ($teacherActiveRate) {
                return $teacherActiveRate*100;
            } else {
                return 0;
            }
        }catch (XhException $e){
            throw  new \Exception($e->getMessage());
        }
    }

    /**
     * 重要教师使用
     *
     * @param $schoolId
     * @param $month
     * @param null $grade
     *
     * @return int
     * @throws \Exception
     *
     * create by dale  20180928
     */
    public function getImpTchUse($schoolId,$month, $grade = null)
    {
        $sql = "select u.iUserId from XHSys_User as u  LEFT JOIN  XHSys_UserTch as t ON u.iUserId = t.iUserId
                WHERE u.iSchoolId = '{$schoolId}' AND u.iUserType = 4 and  u.bDelete = 0 and u.bDisable = 0 and u.bHistory = 0 and t.bImportant = 1 ";
        if ($grade) {
            $sql .= " and t.iCurGrade = {$grade} ";
        }
        $ids = $this->db->fetchAll($sql);
        $ids = array_column($ids,'iUserId');
        if (!$ids) {
            return 0;
        }
        $source = $this->getTchFixNum($schoolId, $month);
        if (!$source) {
            return 0;
        }
        $schoolConfig = Main::getConfigByName('school');
        if (!isset($schoolConfig['ImpTchStandard'])) {
            throw new \Exception('重要教师使用标准');
        }
        $goalNum = 0;//达标人员
        foreach ($ids as $id) {
            if (isset($source[$id]) && $source[$id] >= $schoolConfig['ImpTchStandard']) {
                $goalNum++;
            }
        }
        return intval($goalNum/count($ids)*100);
    }

    /**
     * 关键教师
     *
     * @param $schoolId
     * @param $month
     * @param null $grade
     *
     * @return int
     * @throws \Exception
     *
     * create by dale  20180928
     */
    public function getExcTchUse($schoolId,$month,$grade=null)
    {
        $sql = "select u.iUserId from XHSys_User as u LEFT JOIN  XHSys_UserTch as t ON u.iUserId = t.iUserId
                WHERE u.iSchoolId = '{$schoolId}' AND u.iUserType = 4 and  u.bDelete = 0 and u.bDisable = 0 and u.bHistory = 0 and t.bExcellent = 1 ";
//                WHERE u.iSchoolId = '{$schoolId}' AND u.iUserType = 4 and  u.bDelete = 0 and u.bCompany = 0 and u.bDisable = 0 and u.bHistory = 0 and t.bImportant = 1 ";
        if ($grade) {
            $sql .= " and  t.iCurGrade = {$grade} ";
        }
        $ids = $this->db->fetchAll($sql);
        $ids = array_column($ids,'iUserId');
        if(count($ids) <= 0){
            return 0;
        }
        $source = $this->getTchFixNum($schoolId,$month);
        if(count($source) <= 0){
            return 0;
        }
        $schoolConfig = Main::getConfigByName('school');
        if(!isset($schoolConfig['ExcTchStandard'])){
            throw new \Exception('优秀教师使用标准');
        }
        $goalNum = 0;//达标人员
        foreach ($ids  as  $id){
            if(isset($source[$id]) && $source[$id] >=$schoolConfig['ExcTchStandard']){
                $goalNum++;
            }
        }
        return intval($goalNum/count($ids)*100);
    }

    /**
     * 获取反馈统计
     *
     * @param $schoolId
     * @param $month
     * @return array|bool|mixed|\stdClass
     *
     * @throws \Exception
     *
     * create by dale 20180423
     */
    private function getFeedback($schoolId,$month){
        $date = explode('-',$month);
        $startDay = mktime(0, 0, 0, $date[1] ,1 , $date[0])*1000;
        $endDay   = mktime(23, 59, 59, $date[1], date('t', $startDay), $date[0]);
        if($endDay > time() ){
            $endDay = mktime(23, 59, 59, $date[1], date('d')-1, $date[0]);
        }
        $endDay = $endDay*1000;
        try{
            $params = [
                'schoolId'  => $schoolId,
                'startTime' => $startDay,
                'endTime'   => $endDay,
            ];
//            $url = 'http://172.21.0.27:9200';
            $url = Main::getConfigByName('feedback')['url'];
            $client = new HttpClient($url);
            $response = $client->get('api/v1/manage/feedback/statistics',$params);
//            var_dump($response);die;
            if(!$response->isSuccess()){
                throw new \Exception($response->body);
            }
            $arr = $response->toArray();
            if (!$arr) {
                $arr = [
                    'totalFeedback' => 0 ,
                    'totalReplied'  => 0
                ];
            }
            return $arr;
        }catch (\Exception $e) {
            throw new \Exception($e->getMessage());
        }
    }

    /**
     * 活动详情
     * @param $iSSNId
     * create by xjq 20180605
     */
    public function actDetailAction($iSSNId){
        $this->view->pick('school_examine/actDetail');
        $enums = [1 => '校际' , 2 => '校内' , 3 => '班级'];
        $node = XhschoolStateNode::findFirst($iSSNId);
        if (!$node ) {
            return $this->sendErrorResponse('活动未生成');
        }
        $data = json_decode($node->mJson , true);
        $school = XhschoolInfo::getSchoolArray();
        $grade  = XhsysEnum::getEnumByNodeName('年级');
        foreach ($data as $index => &$row) {
            $targets = explode(',' , $row['sTargetIds']);
            $num = count($targets);
            if($row['sTag'] == 1){
                $row['grade']  = 10;
                foreach ($targets as &$target){
                    $target = $school[$target];
                }
                unset($target);
                $row['sTargetIds'] = implode(',' , $targets);
            }else if ($row['sTag'] == 2){ //校内、
                $row['grade'] = $num > 1 ?  8 : 5;
                foreach ($targets as &$target){
                    $target = $grade[$target];
                }
                unset($target);
                $row['sTargetIds'] = implode(',' , $targets);
            }else if ($row['sTag'] == 3){
                $row['grade'] = $num > 1 ?  4 : 2;
            }
            $row['sType'] = $enums[$row['sTag']];
        }
        $this->view->setVar('data' , $data);
    }



    /**
     * 获取运营考核分数
     *
     * @param $schoolId
     * @param $month
     * @param $grade
     * @return int
     * @throws \Exception
     *
     * create by dale 20171229
     */
    public function getRunExamine($schoolId, $month, $grade = null)
    {
        $statsModel = XhstatsExamine::findFirst([
//            'columns'    => 'iScore,mScoreInfo,iMode',
            'conditions' => 'bDelete = 0 AND iSchoolId = :schoolId: AND sTargetMonth = :targetMonth:',
            'bind'       => ['schoolId' => $schoolId, 'targetMonth' => $month]
        ]);
        if(!$statsModel){
            return 0;
            throw  new \Exception('运营绩效考核数据未生成');
        }
        if (!$grade) {
            if ($statsModel->iMode == 2) {
                throw new \Exception('存储考核数据为年级,与将要生成全校的运营考核数据不匹配');
            }
            return $statsModel->iScore;
        }
        if ($statsModel->iMode == 1) {
            throw new \Exception('存储考核数据为全校,与将要生成年级的运营考核数据不匹配');
        }
        $gradeEnum = XhsysEnum::getEnumByNodeName('年级');
        $gradeName = Tool::getValue($gradeEnum, $grade, '');
        if (!$gradeName) {
            throw new \Exception('传入未知年级');
        }
        $mSourceInfo = is_array($statsModel->mScoreInfo) ? $statsModel->mScoreInfo : unserialize($statsModel->mScoreInfo);
        if (!$mSourceInfo) {
            return 0;
        } else if (!is_array($mSourceInfo)) {
            throw new \Exception('考核得分反序列化失败');
        }
        $gradeSource = Tool::getValue($mSourceInfo, $gradeName, []);
        if (!$gradeSource) {
            return 0;
        }
        $totalScore = 0;
        foreach ( $gradeSource as $index => $score) { //得分
            $totalScore += floatval($score);
        }

        return $totalScore;
//        if (strtotime($month) == strtotime(date('Y-m',time())) ){
//            return  0;
//        }

    }

    /**
     * 获取运营案例次数
     *
     * @param $schoolId
     * @param $month
     * @return mixed
     * create by dale 2018/1/2
     */
    public function getRunCase($schoolId,$month){
        $sql = "select count(iSCSId) as num , iArea from XHSchool_CaseShare WHERE  bDelete = 0 AND iSchoolId = {$schoolId} AND DATE_FORMAT(tTime,'%Y-%m') = '{$month}' GROUP BY iArea ";
        return array_column($this->db->fetchAll($sql),'num','iArea');
    }

    /**
     * 获取需求bug次数
     * @param $schoolId
     * @param $month
     * @return mixed
     *
     * create by dale 2018/1/2
     */
    public function getTaskNum($schoolId,$month){
        $sql = "select count(iTTId) as num from XHTrack_Task WHERE  sSchoolId like '%,".$schoolId.",%' AND DATE_FORMAT(tCreateDate,'%Y-%m') = '{$month}' AND bDelete =0 ";
        return $this->db->fetchOne($sql)['num'];
    }
    /**
     * 获取周报次数
     * @param $schoolId
     * @param $month
     * @return mixed
     *
     * create by dale 2018/1/2
     */
    public function getWeekGrade($schoolId,$month){
        $grade = XhsysGrade::findFirst([
            'conditions' => 'bDelete = 0 and sMonth = :month: and iTargetId = :schoolId: and iType = 2 ',
            'bind'       => ['month' => $month , 'schoolId' => $schoolId ],
        ]);
        if (!$grade) {
            return 0;
        }
        return Tool::getValue($grade->toArray(),'iGrade',0);
    }

    /**
     * 获取教师日志
     * @param $schoolId
     * @param $month
     * @param $grade
     * @return mixed
     *
     * create by dale 2018/1/2
     */
    public function getLogNum($schoolId,$month,$grade = null)
    {
        $sql = "select t.* from XHTrack_Tch as t LEFT JOIN XHSys_User as u ON u.iUserId = t.iUserId LEFT JOIN XHSys_UserTch as ut ON ut.iUserId = u.iUserId    WHERE u.iSchoolId = {$schoolId} AND DATE_FORMAT(t.tTrackTime,'%Y-%m') = '{$month}' AND t.bDelete = 0 AND t.iState = 2 AND ut.bStatsLog = 1 ";
        if ($grade) {
            $sql .= " AND ut.iCurGrade = {$grade}  ";
        }
        $sql.= "  GROUP BY t.iUserId";
        $sql = "select count(a.iUserId) as num from ({$sql}) as a";
//        var_dump($this->db->fetchOne($sql));die;
        return $this->db->fetchOne($sql)['num'];
    }


    /**
     * 学校运营考核列表
     *
     * @return \Phalcon\Mvc\View
     * create by dale 20171226
     */
    public function schoolExamineListAction(){
//        $this->view->setTemplateBefore('listForm');
        $this->view->pick('school_examine/schoolExamineList');
        Assets::xhChart();
        Assets::easyUI('js/school_examine/schoolExamineList.js');
        Assets::importMainJs('assets/easyui/datagrid-detailview.js');
        $listButtonArr = $listSearchArr = [];
        $startMonth = Main::getConfigByName('school')['startMonth'];
        if(!$startMonth){
            $this->sendViewError('没有设置开始月份');
        }
        $nowMonth = date('Y-m' , strtotime('this month'));
        $month = $this->getMonth($startMonth,$nowMonth);
        $dep = XhhrmDepart::findFirst([
            'columns'    => 'iDepId,sDepName',
            'conditions' => 'bDelete = 0 AND sTag = :sTag:',
            'bind'       => ['sTag'=>'XHYYB']
        ]);
        $area = XhhrmDepart::find([
            'columns'    => 'iDepId,sDepName,iParentId',
            'conditions' => 'bDelete = 0 AND iParentId = :iParentId:',
            'bind'       => ['iParentId'=>$dep->iDepId],
        ]);
        $area = array_column($area->toArray(),'sDepName','iDepId');
        $area[''] = '--请选择区--';
        $city[''] = '--请选择市--';
        $level = self::$runLevel;
        $level[''] = '考核等级';
//        $examineMode = XhschoolInfo::find([
//            'columns'    => 'iExamineMode,iSchoolId',
//            'conditions' => 'bDelete = 0',
//            'bind'       => ['id' => $schoolId],
//        ])->toArray();
        $listSearchArr[] = array('type' => 'select', 'id' => 'list_search_mode', 'data' => [0 => '考核方式', 1 => '全校', 2 => '年级'],'default' => 0 );
        $listSearchArr[] = array('type'=>'select', 'id'=>'list_search_date', 'data'=>$month,'default'=>$nowMonth);
        $listSearchArr[] = array('type'=>'select', 'id'=>'list_search_level', 'data'=>$level,'default'=>'');
        $listSearchArr[] = array('type'=>'select', 'id'=>'list_search_area', 'data'=>$area,'default'=>'');
        $listSearchArr[] = array('type'=>'select', 'id'=>'list_search_city', 'data'=>$city,'default'=>'');
        $listSearchArr[] = array('type'=>'text', 'id'=>'list_search', 'label'=>'  搜索： ');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_search', 'text' => '查找', 'icon' => 'fa-search');
        $listSearchArr[] = array('type' => 'button', 'id' => 'bt_list_export', 'text' => '导出', 'icon' => 'fa fa-file-excel-o');
        if(UserPower::checkUserPower('School_RunState_Edit')){
            $listButtonArr[] = array('plain'=>'true' ,'id'=>'bt_list_add', 'text'=>'生成', 'icon'=>'fa-plus');
        }
        $listButtonArr[] = array('plain'=>'true' ,'id'=>'bt_list_pack', 'text'=>'一键收起', 'icon'=>'fa-compress');
        $listButtonArr[] = array('plain'=>'true' ,'id'=>'bt_list_expand', 'text'=>'一键展开', 'icon'=>'fa-expand');
        return $this->view->setVars(array(
            'List'       => Template::createList('list', 'XHSchool_Examine', [
                'searchToolbar' => Template::createSearchToolBar($listSearchArr, !!$listButtonArr),
                'buttonToolbar' => Template::createButtonToolBar($listButtonArr)
            ]),
            'power' => UserPower::checkUserPower('School_RunState_Edit'),
            'Grade' => Template::createList('gradeList', 'XHSchool_Grade')
        ));
    }

    /**
     *
     * @param $startMonth
     * @param $nowMoth
     * @return array
     * create by xjq 20180512
     */
    public function getMonth($startMonth , $nowMoth){
        $startDate = strtotime($startMonth);
        $endDate   = strtotime($nowMoth);
        $monthCount = (intval(date('Y',$endDate)) - intval(date('Y',$startDate))) * 12 + (intval(date('m',$endDate))  - intval(date('m',$startDate)));
        $month = [];
        $month[date('Y-m',$startDate)] = date('Y-m',$startDate);
        for ($i = 0 ; $i< $monthCount  ; $i++ ) {
            $month[date("Y-m", strtotime('+1 month',$startDate))] = date("Y-m", strtotime('+1 month',$startDate));
            $startDate = strtotime('+1 month',$startDate);
        }
        return $month;
    }

    /**
     * 获取数据
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale 20171226
     */
    public function getDgDataAction(){
        $sMonth = $this->request->getPost('month','string');
        $key    = $this->request->getPost('key','string');
        $city   = $this->request->getPost('city','string');
        $area   = $this->request->getPost('area','string');
        $order  = $this->request->getPost('order','string');
        $sort   = $this->request->getPost('sort','string');
        $level  = $this->request->getPost('level' , 'string');
        $mode   = $this->request->getPost('mode', 'string');
        if (!$sMonth) {
            return $this->sendErrorResponse(400,'缺少参数');
        }
        try {
//            $grades = $builder2->getQuery()->execute()->toArray();
            $builder = $this->modelsManager->createBuilder()
                ->columns('i.iSchoolId,i.sSchoolName,i.iStatus,e.iSSId,e.sMonth,e.iTotalGrade,e.iLevel,i.iExamineMode')
                ->from(['i' => '\\Admin\\Models\\school\\XhschoolInfo'])
                ->leftJoin('Admin\\Models\\school\\XhschoolState', "i.iSchoolId = e.iSchoolId and e.sMonth = '{$sMonth}' and e.sGrade = '全校'  ", 'e')
                ->where('i.iStatus = 2 and i.bDelete = 0');  //获取运营学校
//            var_dump($builder->getQuery()->execute()->toArray());die;
            $staff = false;
            if ($city || $area) {
                $depId = $city ?: $area;
                $staff = $this->db->fetchOne("select iUserId as userId from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$depId},%'");
            }
//            $schoolIds = School::getPower(false ,$staff ? $staff['userId'] : null );
            $schoolIds = School::getMergePower($staff ? $staff['userId'] : null, false);
            if($schoolIds !== true){
                $schoolIds = implode(',', $schoolIds);
                $builder->andWhere("i.iSchoolId in ({$schoolIds}) ");
            }

            if ($key) {
                $builder->andWhere("i.sSchoolName like '%{$key}%' or i.iSchoolId like  '%{$key}%' ");
            }
            if ($mode) {
                $builder->andWhere('i.iExamineMode = :iExamineMode:', ['iExamineMode' => $mode]);
            }
//            if ($sMonth) {
//                $builder->andWhere("e.sMonth = '{$sMonth}' or e.sMonth is null ");
//            }
            if ($level) {
                $builder->andWhere(' e.iLevel = :level: ' , ['level' => $level] );
            }
            if ($order && $sort) {
                $sort = $sort == 'sGrade' ? 'iTotalGrade' : $sort;$sort = $sort == 'sGrade' ? 'iTotalGrade' : $sort;
                $builder->orderBy( "e.{$sort}  {$order} ");
            }
            $data = Main::runBuilderPage($builder);
            $ids = array_column($data['rows'],'iSchoolId');
            $extra = $this->getChart($ids);
            foreach ($data['rows'] as $index => $rows) {
                $data['rows'][$index]['sMonth'] = '<small class="badge badge-success badge-square " title="">' . $data['rows'][$index]['sMonth'] . '</small>';
                $data['rows'][$index]['extra']  = $extra[$rows['iSchoolId']];
                if (isset($data['rows'][$index]['iTotalGrade'])) {
                    $data['rows'][$index]['sGrade'] = $this->getRunLevel($data['rows'][$index]['iTotalGrade']);
                    $data['rows'][$index]['operate'] = '重新生成';
                } else {
                    $data['rows'][$index]['operate'] = '生成';
                }
            }
            return $this->sendJsonResponse($data);
        }
        catch (\Exception $e) {
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 老师，学生月活跃数据库
     *
     * @return \mysqli
     * @throws \Exception
     *
     * create by dale 20171229
     */
    public function getConnect(){
        $schoolActive = Main::getConfigByName('schoolActive');
        $ip         = $schoolActive['ip'];
        $dbAccount  = $schoolActive['dbAccount'];
        $dbPassword = $schoolActive['dbPassword'];
        $useDbName  = $schoolActive['useDbName'];
        $conn = new Mysql([
            'host'      => $ip,
            'username'  => $dbAccount,
            'password'  => $dbPassword,
            'dbname'    => $useDbName,
            'charset'   => 'utf8'
        ]);
//        $conn = new \mysqli($ip,$dbAccount,$dbPassword,$useDbName);
//        $conn->query('set names "utf8"');
//        if ($conn->connect_error) {
//            throw new \Exception("连接失败: " . $conn->connect_error);
//        }
        if (!$conn) {
            throw new \Exception('学校活跃度库连接失败！');
        }
        return $conn;
    }


    /**
     * 成绩详情
     *
     * @param $schoolId
     * @param $month
     * @param $showBack
     * @return string
     *
     * create by dale 20180102
     */
    public function gradeDetailAction($schoolId, $month, $showBack = false){
        $this->view->pick('school_examine/gradeDetail');
        Assets::importMainJs('assets/xh/xhTop.js');
        Assets::importJs('js/school_examine/gradeDetail.js');
        if(!$schoolId || !$month){
            return $this->sendViewError('缺少参数');
        }
//        $school = XhschoolInfo::findFirst($schoolId);
        $info =  XhschoolState::findFirst([
            'columns'    => 'iSSId,iSchoolId,sMonth,iTotalGrade,iMode',
            'conditions' => 'bDelete = 0  AND iSchoolId = :iSchoolId: AND sMonth = :sMonth: AND sGrade = :sGrade:',
            'bind'       => ['iSchoolId' => $schoolId, 'sMonth' => $month, 'sGrade' => '全校'],
        ]);
        if(!$info){
            return $this->sendViewError('找不到该记录');
        }


//        if ($school->iExamineMode != $info->iMode) {
//            return $this->sendViewError('该记录考核方式与学校考核方式不匹配，请重新生成');
//        }
        try{
            $schoolName = XhschoolInfo::getSchoolNameById($schoolId);

            if ($info->iMode == 1) {
                $nodes = XhschoolStateNode::find([
                    'conditions' => 'bDelete = 0  AND iSSId = :iSSId:',
                    'bind'       => ['iSSId' => $info->iSSId],
                ])->toArray();
                $detail = [
                    'id'       => $info->iSSId,
                    'schoolId' => $info->iSchoolId,
                    'month'    => $info->sMonth,
                    'nodes'    => $nodes,
                    'totalGrade' => $info->iTotalGrade,
                    'schoolName' => $schoolName
                ];
                $this->view->setVar('detail', $detail);
                $lastTime = XhschoolStateNode::findFirst([
                    'columns'    => 'tLastModifyDate',
                    'conditions' => 'bDelete = 0  AND iSSId = :iSSId:',
                    'bind'       => ['iSSId' => $info->iSSId],
                    'order'      => 'tLastModifyDate desc' ,
                ]);
                $this->view->setVar('lastTime', $lastTime->tLastModifyDate);

//                echo '<pre>';
//                print_r($detail);exit;
            } else if ($info->iMode == 2 ) {
                $gradeArr = $this->getSchoolGrade($schoolId);
                if (!$gradeArr) {
                    $this->sendViewError('无法计算平均分，该学校没有分年级');
                }
                $gradeEnum = XhsysEnum::getEnumByNodeName('年级');
                foreach ($gradeArr as &$grade) {
                    $grade = $gradeEnum[$grade];
                }
                unset($grade);
                $statsArr =  XhschoolState::find([
//                    'columns'    => 'iSSId,iSchoolId,sMonth,iTotalGrade,iMode',
                    'conditions' => 'bDelete = 0  AND iSchoolId = :iSchoolId: AND sMonth = :sMonth: AND sGrade in ({gradeArr:array}) ',
                    'bind'       => ['iSchoolId' => $schoolId, 'sMonth' => $month, 'gradeArr' => $gradeArr],
                ])->toArray();
                $detailArr = [];
                if (!$statsArr) {
                    return $this->sendViewError('未生成年级数据');
                }
                foreach ($statsArr as $stats) {
                    $nodes = XhschoolStateNode::find([
                        'conditions' => 'bDelete = 0  AND iSSId = :iSSId:',
                        'bind'       => ['iSSId' => $stats['iSSId']],
                    ])->toArray();
                    $lastTime = XhschoolStateNode::findFirst([
                        'columns'    => 'tLastModifyDate',
                        'conditions' => 'bDelete = 0  AND iSSId = :iSSId:',
                        'bind'       => ['iSSId' => $stats['iSSId']],
                        'order'      => 'tLastModifyDate desc' ,
                    ]);
                    $detail = [
                        'id'       => $stats['iSSId'],
                        'schoolId' => $stats['iSchoolId'],
                        'month'    => $stats['sMonth'],
                        'nodes'    => $nodes,
                        'totalGrade' => $stats['iTotalGrade'],
                        'lastTime'   => $lastTime->tLastModifyDate,
                        'schoolName' => $schoolName
                    ];
                    $detailArr[] = $detail;
                }
                $this->view->setVar('tabArr', array_column($statsArr, 'sGrade'));
//                var_dump(array_column($statsArr, 'sGrade'));die;
                $this->view->setVar('detailArr', $detailArr);

//                echo '<pre>';
//                print_r($detail);exit;
            }


        }catch (\Exception $e){
            return $this->sendViewError($e->getMessage());
        }
        if ($showBack) {
            $viewArr['showBack'] = '<a class="btn btn-default pull-right" id="back" nodeId="'.$schoolId.'" style="margin-right: 10px;" >返回</a>';
        }
        $viewArr['schoolId'] = $schoolId;
        $viewArr['isAdmin']  = \Helpers\User::isAdmin();
        $viewArr['hasPower'] = UserPower::checkUserPower('School_RunState_EditNode');
        return $this->view->setVars($viewArr);
    }



    /**
     * 历年成绩
     *
     * @param $schoolId
     * @return string
     *
     * create by dale 2018/1/2
     */
    public function yearGradeAction($schoolId){
        try{
            $this->view->pick('school_examine/yearGrade');
            Assets::importJs('js/school_examine/yearGrade.js');
            if(!$schoolId){
                return $this->sendViewError('缺少学校id');
            }
            $infos = XhschoolState::find([
                'conditions' => 'bDelete = 0 AND iSchoolId = :schoolId:',
                'bind'       => ['schoolId' => $schoolId],
                'order'      => 'sMonth desc',
            ])->toArray();
            if(count($infos) <= 0){
                return $this->sendViewError('没有运营考核记录');
            }
            foreach ($infos as $index => $info) {
                $infos[$index]['runLevel'] = $this->getRunLevel($info['iTotalGrade']);
                $infos[$index]['goDetail'] = '<a class="goDetail" nodeId="'.$info['iSchoolId'].'"  month="'.$info['sMonth'].'" >点击转至详情</a>';
            }
            $this->view->setVars([
                'infos' => $infos
            ]);
        }catch(\Exception $e){
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 获取该学校老师的布置次数 (所有应用)
     *
     * @param $schoolId
     * @param $month
     * @return array
     * create by dale 2018/1/10
     */
    public function getTchFixNum($schoolId,$month){
//        $schoolId = 4107;
//        $month    = '2018-05';
        $obj = XhstatsExamine::findFirst([
            'conditions' => 'bDelete = 0 and sTargetMonth = :sTargetMonth: and iSchoolId = :schoolId: ',
            'bind'       => ['sTargetMonth' => $month , 'schoolId' => $schoolId],
        ]);
        if(!$obj){
            return [];
        }
        $mStastInfo = $obj->mStatsInfo;
        if (is_string($mStastInfo)) {
            $mStastInfo = $mStastInfo ? unserialize($mStastInfo) : [];
        }
        $arr = [];
        if ($mStastInfo) {
            //进入 common brush chineseBasic speakTrain
            foreach ($mStastInfo['common'] as $row){
                $arr[$row['tchId']]  = isset($arr[$row['tchId']]) ? $arr[$row['tchId']] : 0;
                $arr[$row['tchId']] += intval($row['cloudTask']['taskFixNum']);
                $arr[$row['tchId']] += intval($row['ztClass']['taskValidNum']);
            }
            foreach ($mStastInfo['speakTrain'] as $row){
                $arr[$row['tchId']]  = isset($arr[$row['tchId']]) ? $arr[$row['tchId']] : 0;
                $arr[$row['tchId']] = intval( $arr[$row['tchId']]) + intval($row['taskFixNum']);
            }

            foreach ($mStastInfo['brush']  as $subjects) {
                foreach ($subjects as $row){
                    $arr[$row['tchId']]  = isset($arr[$row['tchId']]) ? $arr[$row['tchId']] : 0;
                    $arr[$row['tchId']] += intval($row['taskFixNum']);
                }
            }
            foreach ($mStastInfo['chineseBasic']  as $row){
                $arr[$row['tchId']]  = isset($arr[$row['tchId']]) ? $arr[$row['tchId']] : 0;
                $arr[$row['tchId']] += intval($row['taskFixNum']);
            }
        }
        return $arr;
//        $stateSchool = new StatsschoolController();
//
//        $dateArr = explode('-',$month);
//        $startTime = date('Y-m-d',mktime(0, 0, 0, $dateArr[1],1 , $dateArr[0]));
//        $endTime   = date('Y-m-d',mktime(0, 0, 0, (($dateArr[1]+1)%12),1 , date('Y'))-24*3600);
//        $endTime   = $this->checkEndDate($endTime);
//        $list = $stateSchool->getStatsAppInfo();//获取统计应用列表  ['CA104001'=>'智通课堂']
//        $arr = [];
//        foreach ($list as $index => $value){
//            try {
//                $appSource = $this->getAppUsageInfo($index,$startTime, $endTime, $schoolId);
//                if (count($appSource) > 0) {
//                    foreach ($appSource as $key => $val){
//                        $arr[$val['tchId']]  = isset($arr[$val['tchId']]) ?:0;
//                        $arr[$val['tchId']] += intval($val['taskFixNum']);
//                    }
//                }
//            }catch (\Exception $e) {
//                continue;
//            }
//
//        }
//        return $arr;
    }


//    public function getTestAction(){
//        $schoolId = 4107;
//        $month    = '2018-05';
//        $obj = XhstatsExamine::findFirst([
//            'conditions' => 'bDelete = 0 and sTargetMonth = :sTargetMonth: and iSchoolId = :schoolId: ',
//            'bind'       => ['sTargetMonth' => $month , 'schoolId' => $schoolId],
//        ])->toArray();
//        return $this->sendJsonResponse($obj['mStatsInfo']);
//    }


    public function getAppUsageInfo($appCode,$startTime, $endTime, $schoolId = null)
    {
        if(isset(Main::getConfigByName('stats_' . $appCode)['readDB'])){
            $config = Main::getConfigByName('stats_' . $appCode)['readDB'];
        }else{
            return [];
        }
        $config = explode('|' ,$config);
        $conn = new Mysql([
            'host'      => $config[0],
            'username'  => $config[1],
            'password'  => $config[2],
            'dbname'    => $config[3],
            'charset'   => $config[4]
        ]);
        if (!$conn) {
            throw new \Exception($appCode . '统计库连接失败！');
        }
        //刷题
        if (in_array($appCode, ['CA101001','CA101002','CA101007', 'CA101008'])) {
            $sql = "SELECT iTchId as tchId,SUM(iTaskFixNum) AS taskFixNum FROM XHApp_SchoolStats WHERE  tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' AND iSchoolId = '{$schoolId}' GROUP BY iTchId";
        }
        //云作业，课堂
        else if (in_array($appCode, ['CA103001','CA103001-3','CA104001'])) {
            $sql = "SELECT iTchId AS tchId,SUM(iTaskRealFixNum) AS taskFixNum FROM (SELECT iTchId,iTaskRealFixNum,iTaskRealTopicNum,SUM(iPracticeNum) AS iPracticeNum,iLastFixTime FROM XHApp_SchoolStats WHERE  tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' AND iSchoolId = '{$schoolId}' GROUP BY tTargetDate,iTchId,iCoId) A GROUP BY iTchId";
        }
        else {
            $sql = "SELECT iTchId as tchId,SUM(iTaskFixNum) AS taskFixNum FROM XHApp_SchoolStats WHERE  tTargetDate >= '{$startTime}' AND tTargetDate <= '{$endTime}' AND iSchoolId = '{$schoolId}' GROUP BY iTchId";
        }
        $tchApp = $conn->fetchAll($sql);
        return $tchApp;
    }


    public function getDepsAction($pId = null)
    {
        $arr = [];
        if ($pId) {
            $data = XhhrmDepart::getDeps($pId);
            $arr[] = [ 'id'=> '','text'=>'--请选择市--' ];
            if ($data) {
                foreach ($data as $index=>$value){
                    $arr[] = ['id'=> $index,'text'=>$value];
                }
            }
        } else {
            $arr[] = [ 'id'=> '','text'=>'--请选择市--' ];
        }
        return $this->sendJsonResponse($arr);
    }



    /**
     * 柱状图数据
     *
     * @return array
     *
     * create by dale 20180129
     */
    public function getChart($ids)
    {
        if (count($ids) <=  0 ) {
            return [];
        }
        $data = XhschoolState::find([
            'conditions' => 'bDelete = 0 AND iSchoolId in ({ids:array})',
            'bind'       => ['ids' => $ids],
            'order'      => 'sMonth asc',
        ])->toArray();
        $arr = [];
        foreach ($data as $index =>$row){
            $arr[$row['iSchoolId']][] = $row;
        }
        $newArray = [];
        $schoolName =XhschoolInfo::getSchoolSupportArray(true,true);
        foreach ($arr as $schoolId => $row ){
            if(count($row)> 0){
                $xList = array_column($row,'sMonth');
                $series = [['name' => $schoolName[$schoolId],'source'=>'num']];
                $num = array_column($row,'iTotalGrade');
            }else{
                $xList = [];
                $series = [['name' => $schoolName[$schoolId],'source'=>'num']];
                $num = [];
            }
            $newArray[$schoolId] = [
                'num'    => $num,
                'series' => $series,
                'xList'  => array_values($xList)
            ];
        }

        return $newArray;
    }

    /**
     * 教师使用
     *
     * create by dale 20180129
     */
    public function tchUseDetailAction($id = null)
    {
        $this->view->pick('school_examine/tchUseDetail');
        $standard = Main::getConfigByName('school')['tchUseStandard'];
        if (!$id) {
            return $this->sendViewError('缺少id');
        }
        $data = XhschoolStateNode::findFirst($id);
        $data = json_decode($data->mJson, true);
        if (count($data) <= 0){
            return $this->sendViewError('没有数据');
        }
        Main::runUserNameById($data,['userId'=> 'userName'], true);
        $this->view->setVars([
            'standard' => $standard,
            'data'     => $data,
        ]);
    }

    /**
     * 运营详情
     *
     * @param $iSEId
     * @return string
     *
     * create by dale 20180130
     */
    public function runDetailAction($id = null)
    {
        $this->view->pick('school_examine/runDetail');
        if (!$id) {
            return $this->sendViewError('缺少参数');
        }
        $iSSId = XhschoolStateNode::findFirst($id)->iSSId;
        $data = XhschoolState::findFirst([
            'conditions' => 'bDelete = 0 and  iSSId = :iSSId:',
            'bind'       => ['iSSId' => $iSSId]
        ]);
        if (!$data) {
            return $this->sendViewError('找不到记录');
        }
        try{
            $statData = XhstatsExamine::getScoreInfo($data->iSchoolId , $data->sMonth);
//            var_dump($mScoreInfo);die;
            $enum = [
                'common' => '通用科目' ,
                'mathBrush' => '题舟-数学',
                'scienceBrush' => '题舟-科学',
                'englishBrush' => '题舟-英语',
                'chineseBrush' => '题舟-语文',
                'chineseCollBrush' => '题舟-文综',
                'speakTrain'   => '口语训练',
                'chineseBasic' => '语文基础知识'
            ];
            $mScoreInfo = $statData['mScoreInfo'];

            $flag = Tool::getValue($mScoreInfo, 'common', null);
            if (!$flag) {
                $grade = $data->sGrade;
                $gradeInfo = Tool::getValue($mScoreInfo, $grade, []);
                $info = [];
                if ($gradeInfo) {
                    foreach ($gradeInfo as $index => $row){
                        $info[$enum[$index]] = $row;
                    }
                    $this->view->setVars([
                        'mScoreInfo'     => $info,
                    ]);
                } else {
                    return $this->sendViewError('没有该年级下面的考核数据');
                }


//                $tabs = [];
//                $infos = [];
//                foreach ($mScoreInfo as $index => $row){
//                    $tabs[] = $index;
//                    $info = [];
//                    foreach ($row as $key => $value) {
//                        $info[$enum[$key]] = $value;
//                    }
//                    $infos[] = $info;
//                }
//                $this->view->setVars([
//                    'tabs' => $tabs,
//                    'infos' => $infos
//                ]);
//                var_dump($tabs,$infos);die;
            }else if ($flag) {
                $info = [];
                foreach ($mScoreInfo as $index => $row){
                    $info[$enum[$index]] = $row;
                }
                $this->view->setVars([
                    'mScoreInfo'     => $info,
                ]);
            } else {
                $this->sendViewError('未知考核模式');
            }
        }catch (\Exception $e){
            return $this->sendViewError($e->getMessage());
        }

    }

    /**
     * 修改密码
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by xjq 20180514
     * modify by ck 20180521    成绩可修改为0
     */
    public function changeGradeAction(){
        try {
            $id     = $this->request->getPost('id', 'int');
            $grade  = $this->request->getPost('grade', 'int');
            if (!$id || !is_numeric($grade)){
                return $this->sendErrorResponse(400 , '缺少参数');
            }
            $this->db->begin();
            $node = XhschoolStateNode::findFirst($id);
            if ($grade > $node->iMaxGrade){
                return $this->sendErrorResponse(400 , '修改的成绩大于最大成绩');
            }
            $node->iGrade = $grade;
            if (!$node->save()){
                throw new \Exception($node->getError());
            }
            $header = XhschoolState::findFirst($node->iSSId);
            $nodes  = XhschoolStateNode::find([
                'columns'    => 'iGrade',
                'conditions' => 'bDelete = 0 and iSSId = :iSSId:',
                'bind'       => ['iSSId' => $node->iSSId]
            ]);
            $totalGrade = 0 ;
            foreach ($nodes as $row){
                $totalGrade += $row->iGrade ;
            }
            $header->iTotalGrade = $totalGrade ;
            $header->iLevel      = $this->getRunLevel($totalGrade,true);
            if (!$header->save()){
                throw new \Exception($header->getError());
            }
            $this->db->commit();
            return $this->sendSuccessResponse('保存成功');
        }
        catch (\Exception $e){
            $this->db->rollback();
            return $this->sendErrorResponse(500, $e->getMessage());
        }
    }

    /**
     * 保存节点
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by xjq 20180514
     */
    public function lockNodeAction()
    {
        try{
            $id = $this->request->getPost('id', 'int');
            $node = XhschoolStateNode::findFirst($id);
            if (!$node) {
                return $this->sendErrorResponse(500 , '未找到节点');
            }
            if ($node->bLock == 1) {
                return $this->sendErrorResponse(500 , '该节点已经锁定');
            }
            $node->bLock = 1;
            if (!$node->save()) {
                return $this->sendErrorResponse(500 , '保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        }catch (\Exception $e){
            return $this->sendErrorResponse(500 , $e->getMessage());
        }
    }

    /**
     * 解锁
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     *
     * create by dale  20181113
     */
    public function unLockNodeAction()
    {
        try{
            $id = $this->request->getPost('id', 'int');
            $node = XhschoolStateNode::findFirst($id);
            if (!$node) {
                return $this->sendErrorResponse(500 , '未找到节点');
            }
            if ($node->bLock != 1) {
                return $this->sendErrorResponse(500 , '该节点已经解锁');
            }
            $node->bLock = 0;
            if (!$node->save()) {
                return $this->sendErrorResponse(500 , '保存失败');
            }
            return $this->sendSuccessResponse('保存成功');
        }catch (\Exception $e){
            return $this->sendErrorResponse(500 , $e->getMessage());
        }
    }

    /**
     * 锁定全部
     *
     * @return \Phalcon\Http\Response|\Phalcon\Http\ResponseInterface
     * create by xjq 20180514
     */
    public function lockAllAction(){
        try{
            $id = $this->request->getPost('id', 'int');
            $header = XhschoolState::findFirst($id);
            if (!$header) {
                return $this->sendErrorResponse(500 , '未找到父节点');
            }
            $this->db->begin();
            $nodes  = XhschoolStateNode::find([
                'conditions' => 'bDelete = 0 and iSSId = :iSSId:',
                'bind'       => ['iSSId' => $header->iSSId]
            ]);
            foreach ($nodes as $index =>$node ) {
                $node->bLock = 1;
                if (!$node->save()) {
                    $this->db->rollback();
                }
            }
            $this->db->commit();
            return $this->sendSuccessResponse('一键锁定成功');
        }catch (\Exception $e){
            $this->db->rollback();
            return $this->sendErrorResponse(500 , $e->getMessage());
        }
    }

    /**
     * 导出运营状况
     *
     * @return bool|string
     *
     * create by ck 20180523
     */
    public function exportExamineAction(){
        $this->view->disable();
        $month = $this->request->getQuery('month', 'string');
        $area  = $this->request->getQuery('area', 'string');
        $city  = $this->request->getQuery('city', 'string');
        $level = $this->request->getQuery('level' , 'string');
//        $key   = $this->request->getQuery('key', 'string');
        try {
            //学校权限处理
            $staff = false;
            if ($city || $area) {
                $depId = $city ?: $area;
                $staff = $this->db->fetchOne("select iUserId as userId from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$depId},%'");
            }
            $schools = User::getSchoolPower(true, $staff ? $staff['userId'] : null, true);

            //基本信息获取
            $examineQuery = XhschoolState::query()
                ->columns(['iSSId', 'iSchoolId', 'iTotalGrade', 'sMonth','iLevel'])
                ->where('bDelete = 0 AND sMonth = :month:', ['month' => $month]);
            if ($schools !== true) {
                $examineQuery->andWhere('iSchoolId IN ({schoolIds:array})', ['schoolIds' => array_keys($schools)]);
            }
            else {
                $schools = User::getSchool(true);
            }

            if ($level) {
                $examineQuery->andWhere('iLevel = :iLevel:' , ['iLevel' => $level ] );
            }

            $examines = array_column($examineQuery->execute()->toArray(), null, 'iSSId');
            if (!$examines) {
                throw new \Exception('无数据导出');
            }
            foreach ($examines as &$examine) {
                $examine['sSchoolName'] = $schools[$examine['iSchoolId']];
                $examine['sLevel']      = $this->getLevel($examine['iTotalGrade']);
            }
            unset($examine);

            //节点获取
            $nodes = XhschoolStateNode::query()
                ->columns(['iSSId', 'sTag', 'sName', 'iGrade', 'sRealData'])
                ->where('bDelete = 0 AND iSSId IN ({iSSIds:array})', ['iSSIds' => array_keys($examines)])
                ->execute()->toArray();

            //单位处理
            $unit = [
                'tchUse'        => '%',
                'runExamine'    => '分',
                'tchShare'      => '次',
                'pubClass'      => '次',
                'tchActive'     => '%',
                'stuActive'     => '%',
                'runCase'       => '次',
                'exCase'        => '次',
                'task'          => '次',
                'weekly'        => '次',
                'tchLog'        => '次',
                'feedback'      => '次',
                'exTch'         => '',
                'activity'      => ''
            ];
            foreach ($nodes as $node) {
                $examines[$node['iSSId']][$node['sTag']] = $node['sRealData'] . $unit[$node['sTag']] . ' / ' . $node['iGrade'];
            }

            $title = [
                'sSchoolName'   => '学校名称',
                'sMonth'        => '月份',
                'iTotalGrade'   => '总分',
                'sLevel'        => '评级',
                'tchUse'        => '教师使用熟练程度',
                'runExamine'    => '运营绩效考核统计',
                'tchShare'      => '教师交流分享次数',
                'pubClass'      => '公开课次数',
                'tchActive'     => '教师活跃率',
                'stuActive'     => '学生活跃率',
                'runCase'       => '运营案例分享次数',
                'exCase'        => '优秀案例分享次数',
                'task'          => '需求bug资源次数',
                'weekly'        => '周报次数',
                'tchLog'        => '教师日志次数',
                'feedback'      => '反馈回复次数',
                'exTch'         => '重要教师的使用(附加)',
            ];

            $data = [];
            foreach ($examines as $key => $examine) {
                $row = [];
                foreach ($title as $filed => $name) {
                    $row[$filed] = Tool::getValue($examine, $filed);
                }
                $data[] = $row;
            }

            $fileName = '学校运营状况_' . $month;
            Tool::exportExcelOnline($fileName, $title, $data,'xlsx', ['autoWidth' => true, 'header' => ['title' => '学校运营状况（各项得分[实际情况/得分])']]);
            return true;
        }
        catch (\Exception $e) {
            return $this->sendViewError($e->getMessage());
        }
    }

    /**
     * 导出记录
     *
     * create by dale 20180131
     */
//    public function exportExamineAction(){
//        $this->view->disable();
//        $sMonth= $this->request->getQuery('month');
//        $area  = $this->request->getQuery('area');
//        $city  = $this->request->getQuery('city');
//        $key   = $this->request->getQuery('key');
//        try {
//            $builder = $this->modelsManager->createBuilder()
//                ->from(['i' => '\\Admin\\Models\\school\\XhschoolInfo'])
//                ->columns('i.iSchoolId,i.sSchoolName,i.iStatus')
//                ->where('i.iStatus = 2')
//                ->andWhere('i.bDelete = 0');
//            if ($city && $area) {
//                $staffSql = "select  iUserId, sChargeDeps from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$city},%'"; //取第一个
//                $staffs = $this->db->fetchOne($staffSql);
//                $authId = !isset($staffs['iUserId']) ? null : $staffs['iUserId'];
//                $schoolIds = UserPower::getAuthorizationSchool(false, $authId);
//            } else if ($area) {
//                $staffSql = "select  iUserId, sChargeDeps from XHHrm_Staff where CONCAT(',',sChargeDeps,',') like '%,{$area},%'"; //取第一个
//                $staffs = $this->db->fetchOne($staffSql);
//                $authId = !isset($staffs['iUserId']) ? null : $staffs['iUserId'];
//                $schoolIds = UserPower::getAuthorizationSchool(false, $authId);
//            } else {
//                $schoolIds = UserPower::getAuthorizationSchool(false);
//            }
//            if ($schoolIds === false) {
//
//            } else if ($schoolIds !== true) {
//                $schoolIds = implode(',', $schoolIds);
//                $builder->andWhere("i.iSchoolId in ({$schoolIds}) ");
//            }
//
//            $builder2 = $this->modelsManager->createBuilder()
//                ->from(['e' => '\\Admin\\Models\\school\\XhschoolExamine'])
//                ->columns('e.iSEId,e.sMonth,e.iTotalGrade,e.iTchUseRate,e.iRunExamine,e.iTchShareNum,e.iPClassNum,e.iTchActiveRate,e.mFeedback,e.mRunCase,
//                e.iStuActiveRate,e.iKeyTchUse,e.iTotalGrade,e.iRunCaseNum,e.iTaskNum,e.iWeekNum,e.iLogNum,e.iImpTchUse,e.iExcTchUse,e.iSchoolId')
//                ->where('e.bDelete = 0');
//            if ($sMonth) {
//                $builder2->andWhere("e.sMonth = '{$sMonth}' OR e.sMonth is null");
//            }
//            if ($key) {
//                $builder->andWhere("i.sSchoolName like '%{$key}%'");
//            }
//            $grades = $builder2->getQuery()->execute()->toArray();
//            if (count($grades) > 0) {
//                $grades = array_column($grades, null, 'iSchoolId');
//            }
//            $data = $builder->getQuery()->execute()->toArray();
//            foreach ($data as $index => $rows) {
//                if(isset($grades[$rows['iSchoolId']])){
//                    $data[$index] = array_merge($data[$index],$grades[$rows['iSchoolId']]);
//                    $data[$index]['iTchUseRate']     = $data[$index]['iTchUseRate'].'%/'.$this->getUseGrade($data[$index]['iTchUseRate']);
//                    $data[$index]['iRunExamine']     = $data[$index]['iRunExamine'].'分/'.$this->getRunGrade($data[$index]['iRunExamine']);
//                    $data[$index]['iTchShareNum']    = $data[$index]['iTchShareNum'].'次/'.$this->getShareGrade($data[$index]['iTchShareNum']);
//                    $data[$index]['iPClassNum']      = $data[$index]['iPClassNum'].'次/'.$this->getPClassGrade($data[$index]['iPClassNum']);
//                    $data[$index]['iTchActiveRate']  = $data[$index]['iTchActiveRate'].'%/'.$this->getActiveGrade($data[$index]['iTchActiveRate']);
//                    $data[$index]['iStuActiveRate']  = $data[$index]['iStuActiveRate'].'%/'.$this->getActiveGrade($data[$index]['iStuActiveRate']);
//                    if(isset($data[$index]['mFeedback']) && $data[$index]['mFeedback'] ){
//                        $feedback = json_decode($data[$index]['mFeedback'], true );
//
//                        $data[$index]['iFeedback']  = '总反馈：'.$feedback['totalFeedback'].'次;总回复：'.$feedback['totalReplied'].'次;/'.$this->getFeedbackGrade($feedback);
//                    }else{
//                        $data[$index]['iFeedback']  = '不存在数据';
//                    }
//                    if(isset($data[$index]['mRunCase']) && $data[$index]['mRunCase'] ){
//                        $runCase  = json_decode($data[$index]['mRunCase'] , true);
//                        $data[$index]['iRunCaseNum']     = array_sum(array_values($runCase)).'次/'.($this->getRunCaseGrade($runCase));
//                    }else{
//                        $data[$index]['iRunCaseNum']     = '不存在数据';
//                    }
//
//                    $data[$index]['iKeyTchUse']      = $data[$index]['iKeyTchUse'].'次/'.($data[$index]['iKeyTchUse']  ?: 0);
//                    $data[$index]['iTaskNum']        = $data[$index]['iTaskNum'].'次/'.($data[$index]['iTaskNum'] > 0 ? 2 : 0);
//                    $data[$index]['iWeekNum']        = $data[$index]['iWeekNum'].'次/'.($data[$index]['iWeekNum'] == 4 ? 5 : 0);
//                    $tchStandard   = $this->getTchStandard($rows['iSchoolId']);
//                    $data[$index]['sLevel']          = $this->getLevel( $data[$index]['iTotalGrade']);
//                    $data[$index]['iLogNum']         = '共'.$data[$index]['iLogNum'] .'次/标准'.$tchStandard.'次,得分'.($data[$index]['iLogNum'] >= $tchStandard ? 5 : 0);
//                }
//            };
//
//            $title = [
//                'sSchoolName' => '学校名称',
//                'sMonth' => '月份',
//                'iTotalGrade' => '总分',
//                'sLevel'      => '评级',
//                'iTchUseRate' => '教师使用熟练程度',
//                'iRunExamine' => '运营绩效考核统计',
//                'iTchShareNum' => '教师交流分享次数',
//                'iPClassNum' => '公开课次数',
//                'iTchActiveRate' => '教师活跃率',
//                'iStuActiveRate' => '学生活跃率',
//                'iRunCaseNum'    => '运营案例分享次数',
//                'iTaskNum' => '需求bug资源次数',
//                'iWeekNum' => '周报次数',
//                'iFeedback' => '反馈回复次数',
//                'iLogNum' => '教师日志次数',
//                'iKeyTchUse' => '重要教师的使用(附加)'
//            ];
//
//            $excel = [];
//            foreach ($data as $key => $row) {
//                foreach ($title as $filed => $name) {
//                    $excel[$key][$filed] = isset($row[$filed]) ? $row[$filed] : '';
//                }
//            }
//            $fileName = '学校运营状况_' . $sMonth;
//            Tool::exportExcelOnline($fileName, $title, $excel,'xlsx',['autoWidth'=>true,'header'=>['title'=>'学校运营状况（各项得分[实际情况/得分])']]);
//        }
//        catch (\Exception $e) {
//            return $this->sendErrorResponse(500, $e->getMessage());
//        }
//    }


    /**
     * 学校运营考核详情
     *
     * create by dale 20180259
     */
    public function schoolRunAction(){
        $schoolId = $this->request->getQuery('schoolId');
        $month    = $this->request->getQuery('month');
        $this->view->pick('school_examine/schoolRun');
        Assets::importJs('js/school_examine/schoolRun.js');
        $subjects = XhsysEnum::getEnumByNodeName('学科');
        $sql = "select count(u.iUserId) as num,t.iSubject from  XHSys_User as u LEFT JOIN  XHSys_UserTch as t  
                ON  u.iUserId = t.iUserId WHERE  u.iSchoolId = {$schoolId} AND u.iUserType =4  
                and  u.bDelete = 0 and u.bDisable = 0 and u.bHistory = 0 GROUP BY t.iSubject";
//                and  u.bDelete = 0 and u.bCompany = 0 and u.bDisable = 0 and u.bHistory = 0 GROUP BY t.iSubject";
        $data = $this->db->fetchAll($sql);
        $data = array_column($data,'num','iSubject');
        $total = "select count(iUserId) as num from  XHSys_User WHERE iSchoolId = {$schoolId} AND iUserType =4  
                and  bDelete = 0 and bDisable = 0 and bHistory = 0 ";
//                and  bDelete = 0 and bCompany = 0 and bDisable = 0 and bHistory = 0 ";
        $total = $this->db->fetchOne($total)['num'];
        $arr['教师数'] = $total;
        foreach ($data as $index =>$nums){
            if(isset($subjects[$index])){
                $arr[$subjects[$index]] = $nums;
            }else{
                $arr['未知'] = $nums;
            }
        }
        $total = "select sAdClsName from  XHSys_User WHERE iSchoolId = {$schoolId} AND iUserType =1  
                and  bDelete = 0 and bDisable = 0 and bHistory = 0    GROUP BY sAdClsName ";
//                and  bDelete = 0 and bCompany = 0 and bDisable = 0 and bHistory = 0    GROUP BY sAdClsName ";
        $arr['班级数'] = count($this->db->fetchAll($total));
        $total = "select count(iUserId) as num from  XHSys_User WHERE iSchoolId = {$schoolId} AND iUserType =1  
                and  bDelete = 0 and bDisable = 0 and bHistory = 0 ";
//                and  bDelete = 0 and bCompany = 0 and bDisable = 0 and bHistory = 0 ";
        $arr['学生数'] = $this->db->fetchOne($total)['num'];


        $this->view->setVars([
            'schoolName'=> XhschoolInfo::getSchoolSupportArray(true)[$schoolId],
            'schoolId'  => $schoolId,
            'tchInfo'   => $arr,
            'month'     => $month,
        ]);
    }



}
